<template>
  <div class="consultation-container">
    <!-- 顶部导航 -->
    <div class="header-content">
      <div class="container">
        <div class="breadcrumbs-container">
          <img src="../../assets/1.png" alt="返回主页" class="home-icon" @click="gotohome">
          <span>咨询安排表</span>
        </div>
      </div>
    </div>

    <!-- 主容器：左侧统计 + 中间日历 -->
    <div class="main-container">
      <!-- 左侧栏 -->
      <aside class="sidebar">
        <!-- 统计卡片 -->
        <el-card class="stats-card">
          <div class="stats-header">
            <h3>数据统计</h3>
          </div>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value blue">{{ todayAvailable }}</div>
              <div class="stat-label">今日可预约</div>
            </div>
            <div class="stat-item">
              <div class="stat-value blue">{{ todayBooked }}</div>
              <div class="stat-label">今日已预约</div>
            </div>
            <div class="stat-item">
              <div class="stat-value blue">{{ todayTotal }}</div>
              <div class="stat-label">今日总号数</div>
            </div>
            <div class="stat-item growth">
              <div class="stat-value" :class="weekGrowth.value >= 0 ? 'positive' : 'negative'">{{ weekGrowth }}%</div>
              <div class="stat-label">周同比</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ todayClosed }}</div>
              <div class="stat-label">今日结案</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ renewals }}</div>
              <div class="stat-label">续约</div>
            </div>
          </div>
          <!-- 移除未约图例 -->
          <div class="status-legend">
            <div class="legend-item">
              <span class="dot" style="background-color: #1976d2;"></span>未约满
            </div>
            <div class="legend-item">
              <span class="dot" style="background-color: #ffa000;"></span>约满
            </div>
          </div>
        </el-card>

        <!-- 可预约时间段列表 -->
        <el-card class="time-slots-card">
          <div class="time-slots-header">
            <h3>可预约时间段</h3>
            <div class="empty-state" v-if="timeSlots.length === 0">
              <div class="empty-icon">
                <i class="el-icon-time"></i>
              </div>
              <p>暂无可预约时间段</p>
              <el-button type="primary" @click="addSlotDialogVisible = true">添加时段</el-button>
            </div>
          </div>
          <div
              v-for="slot in timeSlots"
              :key="slot.id"
              class="time-slot"
              :class="{
                 'past': isPast(slot.date, slot.startTime),
                 'full': slot.booked >= slot.capacity
               }"
          >
            <div class="slot-info">
              <div class="slot-time">
                {{ formatDate(slot.date) }} {{ slot.startTime }}~{{ slot.endTime }}
              </div>
              <div class="slot-status">
                <!-- 简化状态颜色：移除未约（#9e9e9e）逻辑 -->
                <span
                    :style="{
                        backgroundColor: slot.booked < slot.capacity
                          ? '#1976d2'
                          : '#ffa000'
                      }"
                    class="status-dot"
                ></span>
                {{ slot.booked }}/{{ slot.capacity }}
              </div>
            </div>
            <div class="slot-actions">
              <el-button
                  type="primary"
                  :icon="Plus"
                  circle
                  size="mini"
                  @click="openBookingDialog(slot)"
                  :disabled="isPast(slot.date, slot.startTime) || slot.booked >= slot.capacity"
              ></el-button>
              <el-button
                  type="danger"
                  :icon="Minus"
                  circle
                  size="mini"
                  @click="cancelBooking(slot)"
                  :disabled="isPast(slot.date, slot.startTime) || slot.booked === 0"
              ></el-button>
            </div>
          </div>
        </el-card>
      </aside>

      <!-- 中间日历区域 -->
      <main class="calendar-section">
        <div class="date-nav">
          <el-button @click="prevDay">‹</el-button>
          <span>{{ currentDisplayDate }}</span>
          <div class="nav-right">
            <el-button @click="nextDay">›</el-button>
            <el-button type="primary" @click="addSlotDialogVisible = true">添加时段</el-button>
          </div>
        </div>

        <el-card class="calendar-card">
          <!-- 日历头部：日期 + 星期 -->
          <div class="calendar-header">
            <div class="day-header" v-for="day in daysOfWeek" :key="day.idx">
              <div class="date-label">{{ day.solarDay }} {{ day.lunar }}</div>
              <div class="week-label">{{ day.name }}</div>
            </div>
          </div>

          <!-- 日历身体：时间轴（1:00~17:00） + 日期列 -->
          <div class="calendar-body">
            <!-- 左侧时间轴 -->
            <div class="time-axis">
              <div class="time-slot" v-for="time in timeAxis" :key="time">
                {{ time }}
              </div>
            </div>

            <!-- 右侧日期列（7列，对应一周） -->
            <div class="date-columns">
              <div class="date-column" v-for="(day, dayIdx) in daysOfWeek" :key="dayIdx">
                <div class="date-cell" v-for="(time, timeIdx) in timeAxis" :key="timeIdx">
                  <div
                      v-for="(slotUser, slotUserIdx) in getSlotUsersForCell(day.date, time)"
                      :key="slotUserIdx"
                      class="booking-marker"
                      :style="{ backgroundColor: slotUser.slot.booked < slotUser.slot.capacity ? '#1976d2' : '#ffa000' }"
                      @click="openUserDetail(slotUser.user, slotUser.slot)"
                  >
                    {{ slotUser.user.name }}<br>({{ slotUser.slot.booked }}/{{ slotUser.slot.capacity }})
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </main>
    </div>

    <!-- 添加时段弹窗（时间范围限制：1:00~17:00） -->
    <el-dialog v-model="addSlotDialogVisible" title="添加时段" width="800px">
      <el-form ref="addSlotFormRef" :model="{ slots: addSlotForm }" :rules="rules" label-width="120px">
        <el-form-item label="时段信息" prop="slots">
          <div
              v-for="(item, index) in addSlotForm"
              :key="index"
              class="slot-row"
          >
            <!-- 开始时间下拉选择框 -->
            <el-select
                v-model="item.startTime"
                placeholder="开始时间"
                style="width: 120px; margin-right: 15px;"
                @change="updateEndTimeOptions(index)"
            >
              <el-option
                  v-for="time in timeOptions"
                  :key="time"
                  :label="time"
                  :value="time"
              />
            </el-select>
            <span class="separator">至</span>
            <!-- 结束时间下拉选择框 -->
            <el-select
                v-model="item.endTime"
                placeholder="结束时间"
                style="width: 120px; margin: 0 15px;"
            >
              <el-option
                  v-for="time in filteredEndTimes(index)"
                  :key="time"
                  :label="time"
                  :value="time"
              />
            </el-select>
            <el-input-number
                v-model="item.capacity"
                :min="1"
                style="width: 100px; margin-right: 15px;"
            />
            <el-button
                :icon="Plus"
                circle
                size="mini"
                @click="addRow"
                :disabled="index !== addSlotForm.length - 1"
            />
            <el-button
                :icon="Minus"
                circle
                size="mini"
                @click="removeRow(index)"
                :disabled="addSlotForm.length === 1"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addSlotDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddSlot">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户预约弹窗 -->
    <el-dialog v-model="userBookingDialogVisible" title="添加用户信息" width="800px">
      <el-form ref="userBookingFormRef" :model="userBookingForm" :rules="userBookingRules" label-width="120px">
        <el-form-item label="基本信息" prop="userName">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName">
                <el-input v-model="userBookingForm.userName" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="userBookingForm.gender">
                  <el-radio :label="'男'">男</el-radio>
                  <el-radio :label="'女'">女</el-radio>
                  <el-radio :label="'不愿透露'">不愿透露</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input-number v-model="userBookingForm.age" :min="1" :max="120" placeholder="请输入年龄"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contact">
                <el-input v-model="userBookingForm.contact" placeholder="电话或微信"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="咨询信息" prop="consultType">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="咨询类型" prop="consultType">
                <el-select v-model="userBookingForm.consultType" placeholder="请选择咨询类型" style="width: 100%;">
                  <el-option label="焦虑抑郁" value="焦虑抑郁"></el-option>
                  <el-option label="人际关系" value="人际关系"></el-option>
                  <el-option label="情感问题" value="情感问题"></el-option>
                  <el-option label="家庭矛盾" value="家庭矛盾"></el-option>
                  <el-option label="自我认知" value="自我认知"></el-option>
                  <el-option label="其他问题" value="其他问题"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="咨询方式" prop="consultWay">
                <el-radio-group v-model="userBookingForm.consultWay">
                  <el-radio :label="'面对面'">面对面</el-radio>
                  <el-radio :label="'线上视频'">线上视频</el-radio>
                  <el-radio :label="'语音通话'">语音通话</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="问题简述" prop="problemDescription">
                <el-input v-model="userBookingForm.problemDescription" type="textarea"
                          :rows="3" placeholder="请简要描述您的问题或需求"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userBookingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserBooking">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情弹窗（美化版） -->
    <el-dialog v-model="userDetailDialogVisible" title="用户咨询详情" width="400px">
      <div class="user-detail">
        <!-- 姓名 + 编号 -->
        <div class="user-header">
          <span class="user-name">{{ userDetail.user.name }}</span>
          <span class="user-code">#{{ userDetail.slot.id }}</span>
        </div>

        <!-- 咨询类型标签 -->
        <div class="tags">
          <span class="tag" v-if="userDetail.user.consultType.includes('焦虑')">焦虑抑郁</span>
          <span class="tag" v-if="userDetail.user.consultType.includes('人际')">人际关系</span>
          <span class="tag" v-if="userDetail.user.consultType.includes('情感')">情感问题</span>
          <span class="tag" v-if="userDetail.user.consultType.includes('家庭')">家庭矛盾</span>
          <span class="tag" v-if="userDetail.user.consultType.includes('自我')">自我认知</span>
          <span class="tag" v-if="userDetail.user.consultType.includes('其他')">其他问题</span>
        </div>

        <!-- 心理量表数据 -->
        <div class="stats">
          <p class="section-title">心理量表</p>
          <p>量表1: {{ userDetail.user.scale1 || '未测试' }}</p>
          <p>量表2: {{ userDetail.user.scale2 || '未测试' }}</p>
        </div>

        <!-- 助理信息 -->
        <div class="assistant">
          <p class="section-title">操作信息</p>
          <p>助理: 黄贞尧</p>
          <p>账号: 15888888888</p>
        </div>

        <!-- 咨询师及时间 -->
        <div class="consultant">
          <p class="section-title">咨询安排</p>
          <p>咨询师: {{ userDetail.slot.consultant || '未分配' }}</p>
          <p>时间: {{ formatDate(userDetail.slot.date) }} {{ userDetail.slot.startTime }}~{{ userDetail.slot.endTime }}</p>
        </div>

        <!-- 咨询次数 -->
        <div class="counts">
          <p class="section-title">咨询次数</p>
          <p>本次: {{ userDetail.slot.users.filter(u => u.name === userDetail.user.name).length }}</p>
          <p>本年: {{ calculateYearlyCount(userDetail.user) }}</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from 'vue';
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElButton, ElCard, ElTimePicker, ElRadio, ElRadioGroup, ElSelect, ElOption, ElSlider, ElRow, ElCol } from 'element-plus';
import { Plus, Minus, Refresh } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { Solar } from "lunar-typescript"; // 导入 Solar 类

// 路由跳转
const router = useRouter();
const gotohome = () => router.push('/index');

// 计算单元格中的预约信息
const getSlotUsersForCell = computed(() => {
  return (date: string, time: string) => {
    return timeSlots.value
        .filter(slot => {
          // 优化日期匹配逻辑，使用时间戳比较
          const slotDate = new Date(slot.date);
          const targetDate = new Date(date);
          const isSameDay =
              slotDate.getFullYear() === targetDate.getFullYear() &&
              slotDate.getMonth() === targetDate.getMonth() &&
              slotDate.getDate() === targetDate.getDate();

          // 优化时间匹配逻辑
          const isSameTime = slot.startTime === time;

          return isSameDay && isSameTime;
        })
        .flatMap(slot =>
            slot.users.map(user => ({ user, slot }))
        );
  };
});

// 生成时间选项（与日历表一致）
const timeOptions = computed(() => {
  const options = [];
  for (let h = 1; h <= 17; h++) {
    options.push(`${h.toString().padStart(2, '0')}:00`);
  }
  return options;
});

// 过滤结束时间选项（只能选择大于开始时间的选项）
const filteredEndTimes = (index: number) => {
  const item = addSlotForm.value[index];
  if (!item.startTime) return [];
  const startIndex = timeOptions.value.indexOf(item.startTime);
  return timeOptions.value.slice(startIndex + 1);
};

// 当开始时间变化时，更新结束时间选项
const updateEndTimeOptions = (index: number) => {
  const item = addSlotForm.value[index];
  if (item.endTime && timeOptions.value.indexOf(item.endTime) <= timeOptions.value.indexOf(item.startTime)) {
    item.endTime = ''; // 清除无效的结束时间
  }
};

// 核心数据
const currentDate = ref(new Date().toISOString().split('T')[0]); // 当前日期（如"2025-07-03"）
const timeSlots = ref<Array<{
  id: number;
  date: string;
  startTime: string;
  endTime: string;
  capacity: number;
  booked: number;
  users: any[]; // 存储预约用户
  consultant?: string; // 咨询师信息
}>>([]);

// 生成1:00~17:00的时间轴（与时间选项一致）
const timeAxis = computed(() => timeOptions.value);

onMounted(() => {
  initTimeSlots();
  generateRandomStats();
});

// 初始化预约数据（初始为空，必须通过添加时段创建）
const generateRandomTimeSlots = (date: string) => {
  return [];
};
const initTimeSlots = () => {
  timeSlots.value = generateRandomTimeSlots(currentDate.value);
};

// 统计数据
const todayAvailable = computed(() =>
    timeSlots.value.reduce((sum, s) => sum + (s.capacity - s.booked), 0)
);
const todayBooked = computed(() =>
    timeSlots.value.reduce((sum, s) => sum + s.booked, 0)
);
const todayTotal = computed(() =>
    timeSlots.value.reduce((sum, s) => sum + s.capacity, 0)
);
const weekGrowth = ref<number>(0);   // 周同比（模拟）
const todayClosed = ref<number>(0);   // 今日结案（模拟）
const renewals = ref<number>(0);      // 续约（模拟）

// 模拟统计数据
const generateRandomStats = () => {
  weekGrowth.value = Math.floor(Math.random() * 21) - 10; // -10% ~ +10%
  todayClosed.value = Math.floor(Math.random() * 10);
  renewals.value = Math.floor(Math.random() * 5);
};

// 动态生成本周7天（含阳历日、农历、星期）
const daysOfWeek = computed(() => {
  const current = new Date(currentDate.value);
  const startOfWeek = new Date(current);
  startOfWeek.setDate(current.getDate() - current.getDay()); // 本周日

  const days = [];
  for (let i = 0; i < 7; i++) {
    const date = new Date(startOfWeek);
    date.setDate(startOfWeek.getDate() + i);

    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份转1-12
    const solarDay = date.getDate();   // 阳历日（如31）

    // 转换为农历
    const solar = Solar.fromDate(date); // 通过 Solar 类转换
    const lunar = solar.getLunar();
    const lunarDay = lunar.getDayInChinese(); // 获取农历日期（如"廿二"）

    days.push({
      name: ['周日','周一','周二','周三','周四','周五','周六'][date.getDay()],
      solarDay,  // 阳历日
      lunar: lunarDay,  // 农历日期
      date: date.toISOString().split('T')[0],
      idx: i,
    });
  }
  return days;
});

// 添加时段弹窗
const addSlotDialogVisible = ref(false);
const addSlotForm = ref([
  { startTime: '', endTime: '', capacity: 1 }, // 初始空行，强制用户填写
]);
const addSlotFormRef = ref<InstanceType<typeof ElForm>>();

// 表单验证规则
const rules = {
  slots: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('至少添加一个时段'));
          return;
        }
        const errors: string[] = [];
        value.forEach((item, i) => {
          // 必填校验
          if (!item.startTime) errors.push(`第${i+1}行开始时间必填`);
          if (!item.endTime)   errors.push(`第${i+1}行结束时间必填`);
          if (item.capacity < 1) errors.push(`第${i+1}行号数不能小于1`);

          // 时间顺序校验
          if (item.startTime && item.endTime) {
            const startIndex = timeOptions.value.indexOf(item.startTime);
            const endIndex = timeOptions.value.indexOf(item.endTime);
            if (startIndex === -1 || endIndex === -1) {
              errors.push(`第${i+1}行时间选择无效`);
            } else if (startIndex >= endIndex) {
              errors.push(`第${i+1}行开始时间必须早于结束时间`);
            }
          }
        });
        errors.length ? callback(new Error(errors.join('；'))) : callback();
      },
      trigger: 'submit',
    },
  ],
};

// 时段操作
const addRow = () => {
  // 自动填充下一个可用时间
  const lastRow = addSlotForm.value[addSlotForm.value.length - 1];
  const nextStartTime = lastRow.endTime || '';
  addSlotForm.value.push({
    startTime: nextStartTime,
    endTime: '',
    capacity: 1
  });
};

const removeRow = (index: number) => {
  if (addSlotForm.value.length > 1) {
    addSlotForm.value.splice(index, 1);
  }
};

const submitAddSlot = () => {
  addSlotFormRef.value?.validate((valid) => {
    if (valid) {
      const newSlots = addSlotForm.value.filter(item => item.startTime && item.endTime);
      const hasDuplicate = newSlots.some((slot, index) =>
          newSlots.slice(index + 1).some(other =>
              other.startTime === slot.startTime && other.endTime === slot.endTime
          )
      );

      if (hasDuplicate) {
        ElMessage.warning('存在重复的时间段');
        return;
      }

      newSlots.forEach(newSlot => {
        timeSlots.value.push({
          id: Date.now(),
          date: currentDate.value,
          startTime: newSlot.startTime,
          endTime: newSlot.endTime,
          capacity: newSlot.capacity,
          booked: 0,
          users: [],
          consultant: '侯曼' // 默认咨询师，实际应从选择器获取
        });
      });

      timeSlots.value.sort((a, b) => a.startTime.localeCompare(b.startTime));
      addSlotDialogVisible.value = false;
      ElMessage.success('时段添加成功');
    }
  });
};

// 用户预约弹窗数据模型
const userBookingDialogVisible = ref(false);
const userBookingForm = ref({
  slotId: 0,
  userName: '',
  gender: '不愿透露',
  age: null,
  contact: '',
  consultType: '',
  consultWay: '面对面',
  urgency: 3,
  problemDescription: ''
});

// 增强的表单验证规则
const userBookingRules = {
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z\s]{2,20}$/, message: '请输入有效姓名', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
  ],
  contact: [
    { pattern: /^1[3-9]\d{9}$|^[a-zA-Z0-9_-]{5,20}$/, message: '请输入正确的手机号或微信账号', trigger: 'blur' }
  ],
  consultType: [
    { required: true, message: '请选择咨询类型', trigger: 'change' }
  ],
  problemDescription: [
    { min: 10, message: '问题描述至少10个字', trigger: 'blur' }
  ]
};
const userBookingFormRef = ref<InstanceType<typeof ElForm>>();

// 提交用户预约
const submitUserBooking = () => {
  userBookingFormRef.value?.validate((valid) => {
    if (valid) {
      const slot = timeSlots.value.find(s => s.id === userBookingForm.value.slotId);
      if (slot) {
        // 构建完整的用户信息对象并存储
        const userInfo = {
          name: userBookingForm.value.userName,
          gender: userBookingForm.value.gender,
          age: userBookingForm.value.age,
          contact: userBookingForm.value.contact,
          consultType: userBookingForm.value.consultType,
          consultWay: userBookingForm.value.consultWay,
          urgency: userBookingForm.value.urgency,
          problemDescription: userBookingForm.value.problemDescription,
          bookingTime: new Date().toISOString(),
          scale1: Math.floor(Math.random() * 40) + 60, // 模拟心理量表1分数(60-100)
          scale2: Math.floor(Math.random() * 40) + 60  // 模拟心理量表2分数(60-100)
        };

        slot.users.push(userInfo);
        slot.booked++;
        userBookingDialogVisible.value = false;
        ElMessage.success('预约成功，用户信息已记录');
      } else {
        ElMessage.error('时段不存在');
      }
    }
  });
};

// 日期切换
const currentDisplayDate = computed(() => {
  const d = new Date(currentDate.value);
  return `${d.getFullYear()}年${(d.getMonth()+1).toString().padStart(2, '0')}月${d.getDate().toString().padStart(2, '0')}日`;
});

const prevDay = () => {
  const d = new Date(currentDate.value);
  d.setDate(d.getDate() - 1);
  currentDate.value = d.toISOString().split('T')[0];
  initTimeSlots();
  generateRandomStats();
};

const nextDay = () => {
  const d = new Date(currentDate.value);
  d.setDate(d.getDate() + 1);
  currentDate.value = d.toISOString().split('T')[0];
  initTimeSlots();
  generateRandomStats();
};

// 辅助方法
const isSameDate = (slotDate: string, targetDate: string) => {
  const s = new Date(slotDate);
  const t = new Date(targetDate);
  return s.getFullYear() === t.getFullYear()
      && s.getMonth() === t.getMonth()
      && s.getDate() === t.getDate();
};

const isPast = (slotDate: string, startTime: string) => {
  const slotTime = new Date(`${slotDate} ${startTime}`);
  return slotTime < new Date();
};

const formatDate = (date: string) => {
  const d = new Date(date);
  return `${d.getFullYear()}/${(d.getMonth()+1).toString().padStart(2, '0')}/${d.getDate().toString().padStart(2, '0')}`;
};

// 格式化用户信息显示
const formatUserInfoForDisplay = (userInfo: any) => {
  if (!userInfo) return '';
  return `${userInfo.name} (${userInfo.consultType})`;
};

// 预约操作
const openBookingDialog = (slot: any) => {
  if (slot.booked >= slot.capacity) {
    ElMessage.warning('该时段已约满');
    return;
  }
  userBookingForm.value.slotId = slot.id;
  // 清空表单并设置默认值
  userBookingForm.value = {
    slotId: slot.id,
    userName: '',
    gender: '不愿透露',
    age: null,
    contact: '',
    consultType: '',
    consultWay: '面对面',
    urgency: 3,
    problemDescription: ''
  };
  userBookingDialogVisible.value = true;
};

const cancelBooking = (slot: any) => {
  if (slot.booked > 0) {
    slot.booked--;
    slot.users.pop(); // 简单处理，实际需根据业务逻辑移除指定用户
    ElMessage.success('取消预约成功');
  }
};

// 用户详情弹窗控制
const userDetailDialogVisible = ref(false);
const userDetail = ref({
  user: {},
  slot: {}
});

// 打开用户详情弹窗
const openUserDetail = (user: any, slot: any) => {
  userDetail.value.user = user;
  userDetail.value.slot = slot;
  userDetailDialogVisible.value = true;
};

// 计算本年咨询次数（模拟）
const calculateYearlyCount = (user: any) => {
  // 实际应从数据库统计该用户本年的咨询次数
  return Math.floor(Math.random() * 10) + 1;
};
</script>

<style scoped lang="scss">
.consultation-container {
  min-height: 100vh;
  background: #f8f9fa;

  .header-content {
    padding: 15px 30px;
    background: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .home-icon {
      width: 24px;
      height: 24px;
      cursor: pointer;
      margin-right: 10px;
    }
  }

  .main-container {
    display: flex;
    gap: 20px;
    margin: 20px 30px;

    .sidebar {
      width: 300px;
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .calendar-section {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
  }

  // 统计卡片
  .stats-card {
    padding: 5px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .stats-header {
      font-size: 18px;
      font-weight: 600;
      padding-bottom: 5px;
      border-bottom: 2px solid #e3f2fd;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 4px;
      margin: 12px 0;
    }

    .stat-item {
      background: #f5f7fa;
      border-radius: 8px;
      padding: 16px;
      text-align: center;

      .stat-value {
        font-size: 24px;
        font-weight: 700;
        margin-bottom: 6px;
      }

      .blue .stat-value {
        color: #1976d2;
      }

      .stat-label {
        font-size: 12px;
        color: #666;
      }
    }

    .positive {
      color: #4caf50;
    }

    .negative {
      color: #f44336;
    }

    .status-legend {
      display: flex;
      gap: 20px;
      font-size: 12px;
      color: #666;
      margin-top: 10px;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;

        .dot {
          width: 10px;
          height: 10px;
          border-radius: 50%;
        }
      }
    }
  }

  // 时间段列表
  .time-slots-card {
    padding: 0;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .time-slots-header {
      padding: 16px 20px;
      font-size: 16px;
      font-weight: 600;
      border-bottom: 1px solid #e0e0e0;
      position: relative;
    }

    .empty-state {
      padding: 40px 0;
      text-align: center;

      .empty-icon {
        font-size: 48px;
        color: #909399;
        margin-bottom: 16px;
      }

      p {
        color: #606266;
        margin-bottom: 20px;
      }
    }

    .time-slot {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid #e0e0e0;

      &:last-child {
        border-bottom: none;
      }

      &.past {
        opacity: 0.6;
      }

      &.full {
        .slot-status .status-dot {
          background-color: #ffa000 !important;
        }
      }

      .slot-info {
        display: flex;
        flex-direction: column;

        .slot-time {
          font-size: 14px;
          color: #333;
          margin-bottom: 4px;
        }

        .slot-status {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #666;

          .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 6px;
          }
        }
      }

      .slot-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  // 日历区域
  .date-nav {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 40px;
    gap: 20px;
  }

  .date-nav span {
    flex: 1;
    text-align: center;

    .current-date {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .nav-right {
    display: flex;
    gap: 10px;
  }

  .calendar-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    height: 1000px;

    .calendar-header {
      display: flex;
      background: #f5f7fa;
      border-bottom: 1px solid #e0e0e0;

      .day-header {
        flex: 1;
        text-align: center;
        padding: 5px 0;

        .date-label {
          font-size: 14px;
          font-weight: 600;
          margin-bottom: 2px;
        }

        .week-label {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .calendar-body {
      display: flex;
      height: 865px;

      .time-axis {
        width: 70px;
        background: #f5f7fa;
        border-right: 1px solid #e0e0e0;

        .time-slot {
          height: 50px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          color: #666;
          border-bottom: 1px solid #e0e0e0;
        }
      }

      .date-columns {
        flex: 1;
        display: flex;
        border-left: 1px solid #e0e0e0;

        .date-column {
          flex: 1;
          border-right: 1px solid #e0e0e0;

          .date-cell {
            height: 50px;
            border-bottom: 1px solid #e0e0e0;
            position: relative;
            cursor: pointer;

            &:hover {
              background: #f5f7fa;
            }

            .booking-marker {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              padding: 4px 8px;
              border-radius: 4px;
              font-size: 10px;
              color: #fff;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              width: 90%;
              text-align: center;
              cursor: pointer;
            }
          }
        }
      }
    }
  }

  // 添加时段弹窗
  .slot-row {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 15px;

    .separator {
      margin: 0 8px;
      color: #999;
    }
  }

  // 优化弹窗样式
  .el-dialog__body {
    padding: 20px 30px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .el-form-item__label {
    font-weight: 500;
  }

  .el-radio-group {
    display: flex;
    gap: 15px;
  }

  .el-slider__runway {
    margin: 10px 0;
  }

  // 用户详情弹窗美化
  .user-detail {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;

    .user-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .user-name {
        font-size: 20px;
        font-weight: 700;
        color: #333;
      }

      .user-code {
        font-size: 14px;
        color: #999;
      }
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 16px;

      .tag {
        padding: 6px 12px;
        background: #e3f2fd;
        border-radius: 20px;
        font-size: 12px;
        color: #1976d2;
      }
    }

    .stats, .assistant, .consultant {
      margin-bottom: 16px;
      padding-bottom: 16px;
      border-bottom: 1px solid #eee;

      .section-title {
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
      }

      p {
        margin: 4px 0;
        font-size: 14px;
        color: #666;
      }
    }

    .counts {
      margin-bottom: 0;

      .section-title {
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
      }

      p {
        margin: 4px 0;
        font-size: 14px;
        color: #666;
      }
    }
  }
}
</style>